
package dk.unet.android.data.sql;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import dk.unet.android.data.UNetDataSource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 *
 * @author Nicolai Willems
 */
public class UnetSQLOpenHelper extends SQLiteOpenHelper {
    private static final String TAG = UnetSQLOpenHelper.class.getName();
    public static final int DATABASE_VERSION = 1;
    public static final String DATABASE_NAME = "unet-ll11.db";

    private static final List<String> CREATE_TABLES;

    static{
        final String createTableExpr = "CREATE TABLE IF NOT EXISTS %s ([ID] INTEGER  NOT NULL PRIMARY KEY AUTOINCREMENT %s );";
        final String createFieldExpr = ", [%s] %s %s";

        CREATE_TABLES = new ArrayList<String>();

        StringBuilder tables = new StringBuilder();

        StringBuilder info_columns = new StringBuilder();

        info_columns.append(String.format(createFieldExpr, "heading", "TEXT", "NOT NULL"));
        info_columns.append(String.format(createFieldExpr, "body", "TEXT"));
        info_columns.append(String.format(createFieldExpr, "data_type", "INTEGER"));

        String info_table = String.format(createTableExpr, "general_info", info_columns.toString());

        CREATE_TABLES.add(info_table);
    }

    public UnetSQLOpenHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.beginTransaction();

        for (Iterator<String> it = CREATE_TABLES.iterator(); it.hasNext();) {
            String createTable = it.next();
            Log.d(TAG, "Executing SQL: "+createTable);
            db.execSQL(createTable);
        }

        db.endTransaction();      
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        //make hundehus
        Log.i(TAG, "Upgrading database from version: "+oldVersion+" to "+newVersion);
        this.onCreate(db);
        Log.i(TAG, "Database upgraded to version: "+newVersion);
    }

    public UNetDataSource getDatabase(boolean canWrite){
        SQLiteDatabase db = null;
        if(canWrite){ db = this.getReadableDatabase();}
        else{ db = this.getWritableDatabase(); }

        UNetDataSource udb = new UNetSQLDataSource(db);
        udb.setWriteable(canWrite);

        return udb;
    }
}
